package changedb;


import java.util.ArrayList;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 *
 * @author Ben Goodwin
 * @version 2.0 16/09/2011
 */
public class MailTo extends javax.swing.JFrame {

    private final MembersList ml;
    private String user, pwd;

    /** Creates new form MailTo */
    public MailTo(MembersList ml) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        this.ml = ml;
        user = JOptionPane.showInputDialog("Email:");
        if (!user.equals("") && user != null) {
            pwd = JOptionPane.showInputDialog("Password:");
            if (!pwd.equals("") && pwd != null) {
                initComponents();
                this.setVisible(true);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        message = new javax.swing.JTextArea();
        leaders = new javax.swing.JCheckBox();
        change = new javax.swing.JCheckBox();
        ignite = new javax.swing.JCheckBox();
        cancel = new javax.swing.JButton();
        send = new javax.swing.JButton();
        subject = new javax.swing.JTextField();
        greeting = new javax.swing.JTextField();
        last = new javax.swing.JCheckBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        toList = new javax.swing.JTextArea();
        first = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Mail-To");

        message.setColumns(20);
        message.setFont(new java.awt.Font("Verdana", 0, 12));
        message.setForeground(new java.awt.Color(204, 204, 204));
        message.setRows(5);
        message.setText("Message\n");
        message.setBorder(null);
        message.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                messageFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                messageFocusLost(evt);
            }
        });
        jScrollPane1.setViewportView(message);

        leaders.setFont(new java.awt.Font("Verdana", 0, 12));
        leaders.setText("Leaders");
        leaders.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                leadersActionPerformed(evt);
            }
        });

        change.setFont(new java.awt.Font("Verdana", 0, 12));
        change.setText("Change");
        change.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeActionPerformed(evt);
            }
        });

        ignite.setFont(new java.awt.Font("Verdana", 0, 12));
        ignite.setText("Ignite");
        ignite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                igniteActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        send.setIcon(new javax.swing.ImageIcon(getClass().getResource("/changedb/images/send.png"))); // NOI18N
        send.setText("Send");
        send.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        subject.setFont(new java.awt.Font("Verdana", 0, 12));
        subject.setForeground(new java.awt.Color(204, 204, 204));
        subject.setText("Subject");
        subject.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        subject.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                subjectFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                subjectFocusLost(evt);
            }
        });

        greeting.setFont(new java.awt.Font("Verdana", 0, 12));
        greeting.setText("Hello");

        last.setFont(new java.awt.Font("Verdana", 0, 12));
        last.setText("Last Name");

        toList.setColumns(20);
        toList.setEditable(false);
        toList.setLineWrap(true);
        toList.setRows(5);
        jScrollPane2.setViewportView(toList);

        first.setBackground(new java.awt.Color(240, 240, 240));
        first.setFont(new java.awt.Font("Verdana", 0, 12));
        first.setText("First Name +");
        first.setBorder(null);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(greeting, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(last))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(leaders)
                        .addGap(18, 18, 18)
                        .addComponent(change)
                        .addGap(18, 18, 18)
                        .addComponent(ignite))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(send)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(cancel))
                        .addComponent(subject, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(110, 110, 110))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(leaders)
                    .addComponent(change)
                    .addComponent(ignite))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(subject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(greeting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(first, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(last))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(send)
                    .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-487)/2, (screenSize.height-472)/2, 487, 472);
    }// </editor-fold>//GEN-END:initComponents

    private void messageFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_messageFocusGained
        if (message.getText().startsWith("Message")) {
            message.setText("");
            message.setForeground(new java.awt.Color(0, 0, 0));
        }
    }//GEN-LAST:event_messageFocusGained

    private void messageFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_messageFocusLost
        if (message.getText().equals("")) {
            message.setForeground(new java.awt.Color(204, 204, 204));
            message.setText("Message");
        }
    }//GEN-LAST:event_messageFocusLost

    private void subjectFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_subjectFocusGained
        if (subject.getText().equals("Subject")) {
            subject.setText("");
            subject.setForeground(new java.awt.Color(0, 0, 0));
        }
    }//GEN-LAST:event_subjectFocusGained

    private void subjectFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_subjectFocusLost
        if (subject.getText().equals("")) {
            subject.setForeground(new java.awt.Color(204, 204, 204));
            subject.setText("Subject");
        }
    }//GEN-LAST:event_subjectFocusLost

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        int answer = JOptionPane.showConfirmDialog(null, "Are you sure you want to cancel without sending?",
                "Cancel?", JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            this.dispose();
        }
    }//GEN-LAST:event_cancelActionPerformed

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendActionPerformed
        ArrayList<Member> members = new ArrayList<Member>();
        int errors = 0;
        String s = new String();
        try {
            if (leaders.isSelected()) {
                for (Member m : ml.getMembersClone("Leader")) {
                    InternetAddress a = new InternetAddress(m.getEmail(), m.getName());
                    try {
                        a.validate();
                        members.add(m);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Email for " + m.getName() + " invalid.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        errors++;
                        s += m.getName() + "\n";
                    }
                }
            }

            if (change.isSelected()) {
                for (Member m : ml.getMembersClone("Change")) {
                    InternetAddress a = new InternetAddress(m.getEmail(), m.getName());
                    try {
                        a.validate();
                        members.add(m);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Email for " + m.getName() + " invalid.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        errors++;
                        s += m.getName() + "\n";
                    }
                }
            }
            if (ignite.isSelected()) {
                for (Member m : ml.getMembersClone("Ignite")) {
                    InternetAddress a = new InternetAddress(m.getEmail(), m.getName());
                    try {
                        a.validate();
                        members.add(m);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Email for " + m.getName() + " invalid.",
                                "Warning", JOptionPane.WARNING_MESSAGE);
                        errors++;
                        s += m.getName() + "\n";
                    }
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
        if (!members.isEmpty()) {
            Properties props = System.getProperties();
            props.put("mail.transport.protocol", "smtp");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            PasswordAuthenticator pa = new PasswordAuthenticator();
            pa.set(user, pwd);
            Session session = Session.getInstance(props, pa);
            String mess = message.getText();
            Message msg;
            try {
                for (Member m : members) {
                    msg = new MimeMessage(session);
                    msg.setFrom(new InternetAddress(user));
                    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(m.getEmail(), m.getName()));
                    msg.setSubject(subject.getText());
                    String me = greeting.getText() + " " + m.getDetails().get(1);
                    if(last.isSelected()) {
                        me += " " + m.getDetails().get(2);
                    }
                    msg.setText(me + "\n\n" + mess);
                    //System.out.println("To: " + m.getEmail() + "\nSubject: " + subject.getText() +
                    //        "\nMessage: " + me + "\n\n" + mess);
                    Transport transport = session.getTransport("smtp");
                    Transport.send(msg);

                    
                }

                msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(user));
                msg.setRecipient(Message.RecipientType.TO, new InternetAddress(user));
                msg.setSubject(subject.getText() + " receipt.");
                String message2 = "Sent message:\n\n" + message.getText() + "\n\nto:\n";
                for (Member m : members) {
                    message2 += m.getName() + " at " + m.getEmail();
                }
                if (errors > 0) {
                    message2 += "\nCould not send to:\n" + s;
                }
                msg.setText(message2);
                Transport.send(msg);

                JOptionPane.showMessageDialog(null, "Sent successfully!\nErrors: " + errors,
                        "Sent", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Something went wrong! :(\nErrors: " + errors,
                        "Error", JOptionPane.ERROR_MESSAGE);
                this.dispose();
            }
        }
    }//GEN-LAST:event_sendActionPerformed

    private void leadersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_leadersActionPerformed
        if(leaders.isSelected()) {
            String s = toList.getText();
                for (Member m : ml.getMembersClone("Leader")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
                toList.setText(s);
        }
        else {
            String s = new String();
            if(change.isSelected()) {
                for (Member m : ml.getMembersClone("Change")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            if(ignite.isSelected()) {
                for (Member m : ml.getMembersClone("Ignite")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            toList.setText(s);
        }
    }//GEN-LAST:event_leadersActionPerformed

    private void changeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeActionPerformed
        if(change.isSelected()) {
            String s = toList.getText();
                for (Member m : ml.getMembersClone("Change")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
                toList.setText(s);
        }
        else {
            String s = new String();
            if(leaders.isSelected()) {
                for (Member m : ml.getMembersClone("Leader")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            if(ignite.isSelected()) {
                for (Member m : ml.getMembersClone("Ignite")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            toList.setText(s);
        }
    }//GEN-LAST:event_changeActionPerformed

    private void igniteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_igniteActionPerformed
        if(ignite.isSelected()) {
            String s = toList.getText();
                for (Member m : ml.getMembersClone("Ignite")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
                toList.setText(s);
        }
        else {
            String s = new String();
            if(leaders.isSelected()) {
                for (Member m : ml.getMembersClone("Leader")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            if(change.isSelected()) {
                for (Member m : ml.getMembersClone("Change")) {
                    if(!m.getEmail().equals("email") && !m.getEmail().equals("")) {
                    s += m.getEmail() + "; ";
                    }
                }
            }
            toList.setText(s);
        }
    }//GEN-LAST:event_igniteActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                MailTo mailTo = new MailTo(new MembersList());
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JCheckBox change;
    private javax.swing.JTextField first;
    private javax.swing.JTextField greeting;
    private javax.swing.JCheckBox ignite;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JCheckBox last;
    private javax.swing.JCheckBox leaders;
    private javax.swing.JTextArea message;
    private javax.swing.JButton send;
    private javax.swing.JTextField subject;
    private javax.swing.JTextArea toList;
    // End of variables declaration//GEN-END:variables
}


class PasswordAuthenticator extends javax.mail.Authenticator {

    private String user, pwd;

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, pwd);
    }

    public void set(String user, String pwd) {
        this.user = user;
        this.pwd = pwd;
    }
}
